package com.joolun.common.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class WxPhoneUtil {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取小程序token
     * @return
     */
    public String geAccessToken() {
        String appId = "wxcee27115c6ccdae7";
        String secret = "3b71c4ead2d8dd7cfa1645ad18b87b07";
        String requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", appId);//小程序appId
        requestUrlParam.put("secret", secret);//小程序 appSecret
//        requestUrlParam.put("js_code", code);//小程序端返回的code
        requestUrlParam.put("grant_type", "client_credential");//默认参数

        //发送post请求读取调用微信接口获取openid用户唯一标识
        //我用的hutool工具包的HttpUtil、JSONUtil,各位按需导入
        JSONObject jsonObject = null;
        String token = null;
        try {
            String result = HttpUtil.get(requestUrl, requestUrlParam);
            jsonObject = JSONUtil.parseObj(result);
            // 获取token
            token = jsonObject.getStr("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    public Object getWxPhone(String code) {
        String appId = "wxcee27115c6ccdae7";
        String secret = "3b71c4ead2d8dd7cfa1645ad18b87b07";
        // 获取token
        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",appId, secret);
        JSONObject token = JSONUtil.parseObj(HttpUtil.get(token_url));
        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getStr("access_token");
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        System.out.println(httpEntity);
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
        Object body = response.getBody();
        return body;

    }

}
